package org.NooLab.itexx.comm.tcp.box.agents;

import java.util.Observable;
import java.util.Observer;


import org.NooLab.itexx.comm.tcp.box.TcpBox;

import org.NooLab.itexx.comm.tcp.box.agents.data.DataIntf;
import org.NooLab.itexx.comm.tcp.box.infra.DataReceiverIntf;
import org.NooLab.itexx.comm.tcp.box.infra.DataSenderIntf;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.objects.StringedObjects;

public class TxpServer {

	 
	public static void main(String[] args) throws Exception {
		
								
		(new TcpPrimaryServer(7209, 7210)).start();
	}

}


class TcpPrimaryServer{

	int senderPort ; 
	int listeningPort ;
	
	TcpBox tcpBox;
	MessageReceiver msgReceiver;

	DataReceiverIntf receiverDevice;
	DataSenderIntf senderDevice;
	
	StringedObjects sob = new StringedObjects();
	PrintLog out = new PrintLog(2,true);
	
	// ========================================================================
	public TcpPrimaryServer( int senderPort, int listeningPort ){
		
		this.senderPort = senderPort;
		this.listeningPort = listeningPort ;
	
		tcpBox = new TcpBox();
		msgReceiver = new MessageReceiver();
	}
	// ========================================================================
	
	
	public void start( ) throws Exception {
		
		senderDevice = tcpBox.createSender(senderPort, listeningPort, "") ;
		receiverDevice = tcpBox.createReceiver(listeningPort, senderPort, msgReceiver, "") ;
	}
	

	class MessageReceiver implements Observer{

		@Override
		public void update(Observable srv, Object dataObj) {
			 
			int r=-1;
			String[] dataPkg;
			
			out.print(2, "S: "+srv.toString().replace("org.NooLab.", "")) ;
			
			dataPkg = (String[])dataObj ;
			
			DataIntf data = (DataIntf)sob.decode( dataPkg[1] );
			Object obj = data.getObject();
			int v = (Integer)obj  ;
			
			out.print(2, "S: "+ v);
					
			out.delay(5000);
			
			v=v+100;
			data.setObject(v);
			
			try {
			
				r = senderDevice.send( sob.encode(data),dataPkg[0]);

				if (r<0){
					
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}
}